package com.myt.matp.gui;

import com.myt.matp.core.Event;

public class UIRow extends UIContainer {

    private int m_Window = 0;

    protected UIRow(int id, GUI gui) {
	super(id, gui);
    }

    public int getType() {
	return UIWidget.ROW;
    }

    protected int getMinHeight() {
	UIWidget uiw;
	int ret = 0;
	for (int i = 0; i < getSize(); i++) {
	    uiw = elementAt(i);
	    ret = Math.max(ret, uiw.getMinHeight());
	}
	return ret;
    }

    protected int getMaxHeight() {
	return getMinHeight();
    }

    protected void resized() {
	UIWidget uiw;
	if (getSize() > 0) {

	    int w = getViewWidth();
	    if (getWindow() > 0) {
		w -= ((getWindow() - 1) * getMarginWidget());
		w = w / getWindow();
	    }
	    else {
		w -= ((getSize() - 1) * getMarginWidget());
		w = w / getSize();
	    }

	    
	    for (int i = 0; i < getSize(); i++) {
		uiw = elementAt(i);
		uiw.resize(w, getHeight());
	    }
	}
    }

    protected int getMarginWidget() {
	return 0;
    }

    protected int typeContained() {
	return UIWidget.UNKNOW;
    }

    public final void setWindow(int window) {
	m_Window = window;
    }

    public final int getWindow() {
	return m_Window;
    }


    public boolean dispatchEventUIContainer(final Event e) {
	boolean ret = true;
	if (!dispatchEventUIRow(e)) {
	    ret = super.dispatchEventUIContainer(e);
	}
	return ret;
    }

    private boolean dispatchEventUIRow(final Event e) {
	boolean ret = false;
	switch (e.getId()) {
	case Event.UI_KEY_RELEASED:
	    ret = eventUIKeyReleased(e);
	    break;
	}
	return ret;
    }

   private boolean eventUIKeyReleased(final Event e) {
	boolean ret = true;
	switch (e.getWParam()) {
	case GUI.KEY_DOWN:
	    postEvent(Event.UI_TAB, GUI.KEY_DOWN);
	    break;
	case GUI.KEY_UP:
	    postEvent(Event.UI_TAB, GUI.KEY_UP);
	    break;
	default:
	    ret = false;
	}
	return ret;
    }


    protected void paintUIContainer(MGraphics g) {
	UIWidget uiw;
	int w;

	w = 0;
	g.setClip(getViewX(), getViewY(), getViewWidth(), getViewHeight());
	for (int i = 0; i < getRedisplay(); i++) {
	    uiw = elementAt(getFrame() + i);
	    uiw.setPosX(getViewX() + w);
	    uiw.setPosY(getViewY());
	    uiw.paint(g);
	    w += (uiw.getWidth() + getMarginWidget());
	}

    }

    protected int computeFrame() {
	UIWidget uiw;
	int ret = 0;
	int w = 0;

	uiw = getFocused();
	if (uiw != null) {
	    ret = indexOf(uiw);
	    do {
		w += uiw.getWidth();

		if (ret == 0) {
		    break;
		}

		uiw = elementAt(--ret);

	    } while (w < getViewWidth());
	}

	return ret;
    }

    protected int computeRedisplay(int frame) {
	return (getWindow() > 0) ? getWindow() : getSize();
    }

}